<template>
  <basic-container>
    <div class="header">
      <TitleComponent mainTitle="用户" subTitle="列表" />
      <el-button text type="primary" @click="router.push('/index')">主页</el-button>
    </div>
    <div class="crud_content">
      <avue-crud ref="crud" v-model="AllData.form" :data="AllData.data" :option="option" :page.sync="AllData.page"
        :table-loading="AllData.loading" @refresh-change="refreshChange" @search-change="searchChange"
        @search-reset="searchReset" @current-change="currentChange" @size-change="sizeChange" @on-load="onLoad">
        <template #menu-left>
          <el-button icon="el-icon-plus" type="primary" @click="addTo">新增</el-button>
        </template>
        <template #menu="{ row }">
          <el-dropdown @command="(command) => handleCommand(command, row)">
            <el-icon size="20" style="rotate: 90deg;cursor: pointer">
              <More />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item command="fundOperation" divided>资金操作</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #mobilePhone="{ row }">
          <div v-if="row.mobilePhone && row.mobilePhone !== ''" class="phone-cell">
            <el-tooltip content="复制手机号" placement="top">
              <el-icon class="copy-icon" size="20" @click="copyToClipboard(row.mobilePhone)">
                <el-icon-document-copy />
              </el-icon>
            </el-tooltip>
            {{ row.mobilePhone }}
          </div>
        </template>
        <template #superNumber="{ row }">
          <el-button type="text" @click="filterByTeam1(row.superNumber)">{{ row.superNumber }}</el-button>
        </template>

        <template #directSubordinatesCount="{ row }">
          <el-button type="text" @click="filterByTeam2(row.directSubordinatesCount)">{{
            row.directSubordinatesCount
          }}
          </el-button>
        </template>

        <template #indirectSubordinatesCount="{ row }">
          <el-button type="text" @click="filterByTeam3(row.indirectSubordinatesCount)">{{
            row.indirectSubordinatesCount
          }}
          </el-button>
        </template>

        <template #disableFlag="{ row }">
          <el-switch v-model="row.disableFlag" :inactive-value="0" style="--el-switch-on-color: #4E9876; "
            @click="handleSwitchChange(row)" />
        </template>

        <template #prohibitWithdrawalFlag="{ row }">
          <el-switch v-model="row.prohibitWithdrawalFlag" :inactive-value="0" style="--el-switch-on-color: #4E9876; "
            @click="handleSwitchChange(row)" />
        </template>

        <template #prohibitBrushOrderFlag="{ row }">
          <el-switch v-model="row.prohibitBrushOrderFlag" :inactive-value="0" style="--el-switch-on-color: #4E9876; "
            @click="handleSwitchChange(row)" />
        </template>
      </avue-crud>
    </div>
    <el-dialog v-model="AllData.addView" :before-close="beforeClose" :title="AllData.tit" append-to-body destroy-on-close
      width="70%">
      <div style="padding: 2%">
        <avue-form ref="formRef" v-model="AllData.formData" :option="optionForm" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button icon="el-icon-circle-check" type="primary" @click="saveSubmit(AllData.tit)">{{
            AllData.tit === '新增' ? '保存' : '修改'
          }}
          </el-button>
          <el-button icon="el-icon-circle-close" @click="beforeClose(() => { AllData.addView = false })">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="AllData.moneyView" append-to-body destroy-on-close width="40%">
      <template #header>
        <div class="my-header">账号:{{ AllData.agentNumbers }}</div>
      </template>
      <div style="padding: 2%">
        <avue-form ref="formRef" v-model="AllData.formMoney" :option="MoneyForm" @submit="saveMoneyData" />
      </div>
    </el-dialog>
    <el-dialog v-model="AllData.confirmDeleteVisible" append-to-body center class="custom-dialog" destroy-on-close
      title="" width="440">
      <div class="swal2-header">
        <div class="swal2-icon swal2-question swal2-animate-question-icon"></div>
        <div class="swal2_fs">确认删除吗？</div>
      </div>
      <div class="swal2_he">ID - {{ AllData.agentNumbers }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="btn btn-primary" type="success" @click="handleDeleteConfirm">
            确认
          </el-button>
          <el-button class="btn" type="" @click="handleDeleteCancel">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="AllData.passwordDialog" title="" width="40%" destroy-on-close center>
      <template #header>
        <div class="header_box">

          修改密码
        </div>
      </template>
      <avue-form v-model="AllData.passwordForm" :option="passworOption" @submit="submitPassword"></avue-form>
    </el-dialog>
  </basic-container>
</template>
<script lang="ts" name="userinfoPage" setup>
import { amountAction, pullDown, userPage, userRemove, userSave, userUpdate, resetPassword } from '@/api/user'
import BasicContainer from "@/components/basic-container/main.vue";
import TitleComponent from "@/components/title/index.vue";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
const router = useRouter();
let crud: any = ref('')
let formRef: any = ref('')
let option: any = reactive({
  height: 'auto',
  calcHeight: 90,
  searchShow: true,
  searchMenuSpan: 6,
  tip: false,
  border: true,
  index: false,
  viewBtn: false,
  editBtn: false,
  delBtn: false,
  addBtn: false,
  dialogWidth: '60%',
  menuWidth: 60,
  menu: true,
  align: 'center',
  dialogTop: 1,
  indexLabel: '序号',
  saveBtnText: '确定',
  refreshBtn: true, // 刷新按钮
  columnBtn: true,
  gridBtn: false,
  searchShowBtn: false,
  dialogMenuPosition: 'center',
  indexWidth: 60,
  column: [
    {
      label: "邀请码",
      prop: "id",
      search: true,
      sortable: true,
      span: 24,
      width: 90,
    },
    {
      label: "所属代理",
      prop: "agentNumber",
      // search: true,
      span: 24,
    },
    {
      label: "头像",
      prop: "avatar",
      type: 'upload',
      dragFile: true,
      dataType: 'string',
      listType: 'picture-card',
      accept: 'image/png, image/jpeg',
      limit: 1,
      span: 24,
      propsHttp: {
        name: 'originalFilename',
        url: 'url',
      },
      headers: {
        Authorization: `Bearer ${userStore.token}`
      },
      tip: '只能上传jpg/png用户头像',
      action: '/prod-api/common/upload'
    },
    {
      label: "手机号",
      prop: "mobilePhone",
      search: true,
      width: 110,
      span: 24,
    },
    {
      label: '团队关系',
      children: [{
        label: '上级',
        search: true,
        prop: 'superNumber'
      }, {
        label: '直推',
        search: false,
        prop: 'directSubordinatesCount',
      }, {
        label: '团队',
        search: false,
        prop: 'indirectSubordinatesCount',
      }]
    },
    {
      label: "余额",
      prop: "balance",
      type: 'number',
      precision: 2,
      span: 24,
    },
    {
      label: "VIP等级",
      prop: "vipLevel",
      search: true,
      filters: true,
      width: 110,
      dataType: 'number',
      filterMethod: function (value, row, column) {
        return row.vipLevel === value;
      },
      span: 24,
      type: 'select',
      dicData: [],
    },
    {
      label: "首次升级时间",
      prop: "firstUpgradeTime",
      span: 24,
      width: 110
    },
    {
      label: "Vip到期时间",
      prop: "vipExpirationTime",
      span: 24,
      width: 110
    },
    // {
    //   label: "注册时间",
    //   prop: "createTime",
    //   search: true,
    //   hide: true,
    //   searchType: 'daterange',
    //   type: "daterange",
    //   format: 'YYYY-MM-DD',
    //   valueFormat: 'YYYY-MM-DD',
    //   startPlaceholder: '开始时间',
    //   endPlaceholder: '结束时间',
    // },
    {
      label: "注册时间",
      prop: "createTime",
      sortable: true,
      span: 24,
      width: 110
    },
    {
      label: "禁用用户",
      prop: "disableFlag",
      span: 24,
      cell: true,
    },
    {
      label: "禁止提现",
      prop: "prohibitWithdrawalFlag",
      span: 24,
      cell: true,
    },
    {
      label: "禁止刷单",
      prop: "prohibitBrushOrderFlag",
      span: 24,
      cell: true,
    },
  ]
})
let passworOption: any = reactive({
  // labelWidth: 150,
  column: [
    {
      label: '新密码',
      prop: 'password',
      type: 'password',
      showPassword: true,
      span: 24,
      rules: [
        {
          required: true,
          message: '请输入新密码',
          trigger: 'blur',
        },
      ],
    }
  ]
})
const display = ref(true)
let AllData: any = reactive({
  rowData: {},
  passwordDialog: false,
  passwordForm: {},
  data: [],
  tit: '',
  names: '',
  indexId: '',
  agentNumbers: '',
  form: {},
  query: {},
  formMoney: {},
  formData: {},
  addView: false,
  loading: false,
  confirmDeleteVisible: false,
  moneyView: false,
  firstLoad: true,// 添加一个标志表示是否是首次加载
  page: {
    pageSize: 10,
    currentPage: 1,
    total: 1
  },
})
let optionForm: any = reactive({
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 100,
  column: [
    {
      label: '代理编号',
      prop: 'agentNumber'
    },
    {
      label: '上级编号',
      prop: 'superNumber'
    },
    {
      label: '用户昵称',
      prop: 'nickname',
      rules: [
        {
          required: true,
          message: '请输入用户昵称',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '等级',
      prop: 'vipLevel',
      type: 'select',
      dataType: 'string',
      dicData: [],
      rules: [
        {
          required: true,
          message: '请选择VIP等级',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '手机号',
      prop: 'mobilePhone',
      span: 24,
      rules: [
        {
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '密码',
      prop: 'password',
      type: 'password',
      display: display,
      rules: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '安全密码',
      prop: 'securityPassword',
      type: 'password'
    },
    {
      label: '头像',
      prop: 'avatar',
      type: 'upload',
      dragFile: true,
      dataType: 'string',
      listType: 'picture-card',
      accept: 'image/png, image/jpeg',
      limit: 1,
      span: 24,
      propsHttp: {
        name: 'originalFilename',
        url: 'url',
      },
      headers: {
        Authorization: `Bearer ${userStore.token}`
      },
      tip: '只能上传jpg/png用户头像',
      action: '/prod-api/common/upload'
    },
    {
      label: '禁止提现',
      prop: 'prohibitWithdrawalFlag',
      type: 'switch',
      value: false,
      dicData: [
        {
          label: '',
          value: false
        }, {
          label: '',
          value: true
        }
      ]
    },
    {
      label: '禁用用户',
      prop: 'disableFlag',
      type: 'switch',
      value: false,
      dicData: [
        {
          label: '',
          value: false
        }, {
          label: '',
          value: true
        }
      ]
    },
    {
      label: '禁用刷单',
      prop: 'prohibitBrushOrderFlag',
      type: 'switch',
      value: false,
      dicData: [
        {
          label: '',
          value: false
        }, {
          label: '',
          value: true
        }
      ]
    },
    {
      label: '邀请码',
      prop: 'invitationCode',
      placeholder:'邀请码自动生成',
      disabled: true
    },
    {
      label: '提现地址',
      prop: 'usdtAddress',
    },
    {
      label: '创建时间',
      prop: "createTime",
      disabled: true,
      dataType: 'string',
      type: "datetime",
    },
  ]
})
let MoneyForm: any = reactive({
  column: [
    {
      label: '资金类型',
      prop: 'amountType',
      span: 24,
      type: 'radio',
      value: '1',
      dicData: [
        {
          label: '余额',
          value: '1'
        },
        {
          label: '冻结资金',
          value: '2'
        },
      ],
      rules: [
        {
          required: true,
          message: '请选择资金类型',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '操作',
      prop: 'actionType',
      span: 24,
      type: 'radio',
      value: '1',
      dicData: [
        {
          label: '增加',
          value: 'ADD'
        },
        {
          label: '减少',
          value: 'REDUCE'
        }
      ],
      rules: [
        {
          required: true,
          message: '请选择操作类型',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '数量',
      prop: 'amount',
      type: 'number',
      precision: 2,
      min: 0,
      max: 9999999,
      rules: [
        {
          required: true,
          message: '请输入数量',
          trigger: 'blur'
        }
      ]
    }
  ]
})
const submitPassword = async (row) => {

  let params = {
    "id": AllData.rowData.id,
    "password": row.password
  }
  await resetPassword(params)
  console.log('row====', row);
  AllData.passwordDialog = false
  ElMessage.success('操作成功');
}
onMounted(() => {
  let vipDicData = option.column.find(item => item.prop === 'vipLevel')
  let vipDicDatas = optionForm.column.find(item => item.prop === 'vipLevel')
  console.log(vipDicData)
  pullDown().then(res => {
    vipDicData.dicData = Object.entries(res.data).map(([key, value]) => ({
      label: value,
      value: key
    }));
    vipDicDatas.dicData = vipDicData.dicData
  })
})

function handleDeleteConfirm() {
  console.log('id>', AllData.indexId)
  userRemove(AllData.indexId).then(res => {
    ElMessage.success('操作成功')
    AllData.confirmDeleteVisible = false
    onLoad(AllData.page)
  }).catch(err => {
    AllData.confirmDeleteVisible = false
  })
}

function handleDeleteCancel() {
  AllData.confirmDeleteVisible = false
}

function onLoad(page: any, params = {}) {
  console.log(userStore, '11')
  AllData.loading = true;
  userPage(page.currentPage, page.pageSize, Object.assign(params, AllData.query)).then((res: any) => {
    const Data = res.data;
    AllData.page.total = Data.total;
    AllData.data = Data.records;
    AllData.loading = false;
  });
}

function beforeClose(done) {
  AllData.addView = false;
  AllData.formData = {}
  done()
}

function refreshChange() {
  onLoad(AllData.page, AllData.query);
}

function searchChange(params: any, done: () => void) {
  AllData.query = params;
  AllData.page.currentPage = 1;
  onLoad(AllData.page, params);
  done();
}

function searchReset() {
  AllData.query = {};
  onLoad(AllData.page);
}

function currentChange(currentPage: any) {
  AllData.page.currentPage = currentPage;
}

function sizeChange(pageSize: any) {
  AllData.page.pageSize = pageSize;
}

function saveMoneyData(form: any, done: any) {
  let params = {
    userId: AllData.indexId,
    amount: form.amount,
    amountType: form.amountType,
    actionType: form.actionType,
  }
  // console.log('aaaa',params);
  
  amountAction(params).then(res => {
    ElMessage.success('操作成功')
    AllData.moneyView = false
    onLoad(AllData.page)
  }).catch(err => {
    AllData.moneyView = false
  })
  done()
}

function saveSubmit(val: any) {
  formRef.value.validate((valid, done) => {
    if (valid) {
      if (val === '新增') {
        AllData.formData.createTime = formatDate(AllData.formData.createTime)
        userSave(AllData.formData).then((res: any) => {
          console.log(res, 'res')
          AllData.addView = false
          AllData.formData = {}
          ElMessage.success('操作成功')
          onLoad(AllData.page)
        }).catch((error) => {
          done()
          ElMessage.error(error.response.data.msg)
        })
      } else {
        userUpdate(AllData.formData).then((res: any) => {
          console.log(res, 'res')
          AllData.addView = false
          AllData.formData = {}
          ElMessage.success('操作成功')
          onLoad(AllData.page)
        }).catch((error) => {
          done()
          ElMessage.error(error.response.data.msg)
        })
      }
      done()
    } else {
      done()
    }
  })
}

function formatDate(dateStr) {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 复制手机号
function copyToClipboard(text: any) {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('复制成功');
  }).catch(() => {
    ElMessage.error('复制失败');
  });
}

function addTo() {
  AllData.tit = '新增'
  AllData.formData.createTime = new Date()
  AllData.addView = true
}

// 根据选择的值来筛选数据
function filterByTeam1(team) {
  // AllData.loading = true;
  // 根据team值来筛选数据
  // AllData.data = AllData.data.filter(item => item.superNumber === team);
  onLoad(AllData.page, { superNumber: team })
  // AllData.loading = false;
}

function filterByTeam2(phone) {
  // AllData.loading = true;
  // // 根据team值来筛选数据
  // AllData.data = AllData.data.filter(item => item.directSubordinatesCount === phone);
  onLoad(AllData.page, { directSubordinatesCount: phone })
  // AllData.loading = false;
}


// 团队有个团队编号，根据团队编号查询
function filterByTeam3(teamNumber) {
  onLoad(AllData.page, { indirectSubordinatesCount: teamNumber })
  // AllData.loading = true;
  // // 根据team值来筛选数据
  // AllData.data = AllData.data.filter(item => item.indirectSubordinatesCount === teamNumber);
  // AllData.loading = false;
}

// 根据操作的命令执行操作
function handleCommand(command, row) {
  AllData.rowData = row
  AllData.indexId = row.id
  AllData.agentNumbers = row.agentNumber
  console.log('command>>', row)
  if (command === 'edit') {
    display.value = false

    AllData.tit = '编辑'
    AllData.formData = row
    AllData.addView = true
  } else if (command === 'delete') {
    AllData.indexId = row.id
    AllData.agentNumbers = row.agentNumber
    AllData.confirmDeleteVisible = true
  } else if (command === 'password') {
    AllData.passwordDialog = true
  }
  else {
    display.value = true

    AllData.indexId = row.id
    AllData.agentNumbers = row.agentNumber
    AllData.names = row.index
    AllData.moneyView = true
  }
}

// 切换选项执行操作
function handleSwitchChange(row) {
  userUpdate(row).then((res: any) => {
    onLoad(AllData.page)
    ElMessage.success('更新成功');
  }).catch((error) => {
  })
}
</script>
<style lang="scss" scoped>
.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 2%;
}

.crud_content {
  width: 100%;
}

.el-dialog__wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.swal2-header {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.swal2-icon {
  position: relative;
  box-sizing: content-box;
  justify-content: center;
  width: 5em;
  height: 5em;
  margin: 1.25em auto 1.875em;
  zoom: normal;
  border: 0.25em solid transparent;
  border-radius: 50%;
  line-height: 5em;
  cursor: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.swal2-icon.swal2-question::before {
  content: "?";
}

.swal2-icon::before {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 92%;
  font-size: 3.75em;
}

.swal2-icon.swal2-question {
  border-color: #c9dae1;
  color: #87adbd;
}

.swal2_fs {
  margin: 0 0 0.4em;
  padding: 0;
  font-size: 25px;
  color: #595959;
  text-align: center;
  font-weight: 400 !important;
}

.swal2_he {
  text-align: center;
  color: #545454;
  font-size: 1.125em;
  font-weight: 300;
  line-height: normal;
  word-wrap: break-word;
}

.btn {
  padding: 0.54rem 1.2rem !important;
  height: 34px;
  line-height: 1.2;
  border-radius: 0.2rem;
  cursor: pointer;
  box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.065),
    0 2px 2px 0 rgba(0, 0, 0, 0.065), 0 1px 5px 1px rgba(0, 0, 0, 0.065);
}

.btn-primary {
  color: #fff;
  background-color: #4e9876;
  border-color: #4e9876;
}
</style>
